package com.bawei.gulimallproduce.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bawei.common.utils.PageUtils;
import com.bawei.common.utils.Query;

import com.bawei.gulimallproduce.dao.CategoryDao;
import com.bawei.gulimallproduce.entity.CategoryEntity;
import com.bawei.gulimallproduce.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> showWithTree() {
        //查询所有类型
        List<CategoryEntity> list = baseMapper.selectList(null);
        //组装父子结构
        //查询1级分类
        List<CategoryEntity> collect = list.stream()
                //条件筛选
                .filter((categoryEntity) ->
                {
                  return   categoryEntity.getParentCid() == 0;
                })
                //属性映射
                .map((menu1) ->{
                            menu1.setChildren(getChildren(menu1, list));
                            return menu1;
                        })
                //排序
                .sorted((menu1,menu2) ->{
                    return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
                })
                //数据收集
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeCateId(List<Long> asList) {
        //TODO待处理
        baseMapper.deleteBatchIds(asList);
    }

    //递归查询子类
    public List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> arr){
        List<CategoryEntity> collect = arr.stream().filter(cate -> {
            return cate.getParentCid() == root.getCatId();
            //映射
        }).map(cate -> {
            cate.setChildren(getChildren(cate, arr));
            return cate;
            //排序
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}